﻿using Saisie_des_prélèvements.Models;
using Saisie_des_prélèvements.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Threading.Tasks;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Saisie_des_prélèvements.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ExportToServerPage : Page
    {
        public ExportToServerPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            

            msg m = new msg();
            txtVerifData.Text = m.export_msg;

            if (!await ValidateUrl(string.Format("{0}{1}", App.AppUri, "GetAllUser")))
            {
                txtVerifData.Text = string.Format(m.login_RecoveryFail, (char)13);
                prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnOK.Visibility = Windows.UI.Xaml.Visibility.Visible;
                return;
            }

            try
            {
                HttpClient hclient = new HttpClient();

                using (var db = new SQLite.SQLiteConnection(App.DBPath))
                {
                    k_export export = new k_export();

                    export.export_date = DateTime.Now;
                    export.user_export = App.CurrentUserId;
                    export.date_create = DateTime.Now;
                    export.tablet_number = App.Marchine;

                    db.Insert(export);

                    export = db.Table<k_export>().OrderByDescending(x => x.export_id).First();

                    //string[] i = db.Table<k_export_client>().Select(c => new k_export_client { export_client_id = c.export_client_id }).AsEnumerable();

                    List<k_client_taken> clients = db.Query<k_client_taken>(
                    "SELECT * FROM k_client_taken WHERE client_taken_id IN (SELECT client_taken_id FROM k_taken WHERE export_client_id IS NULL AND status IN (1,3))");

                    List<k_taken> takens = db.Query<k_taken>(
                    "SELECT * FROM k_taken WHERE export_client_id IS NULL AND status IN (1,3)"); //AND client_taken_id IN (SELECT client_taken_id FROM k_client_taken WHERE signature NOT NULL)");
                    List<k_taken_analyze> analyzes = db.Table<k_taken_analyze>().ToList();

                    foreach (k_client_taken client in clients)
                    {
                        k_export_client ex_client = new k_export_client();

                        ex_client.client_id = client.client_taken_id;
                        ex_client.export_id = export.export_id;
                        ex_client.signature_label = client.signature_label;
                        ex_client.client_signature = Convert.ToBase64String(client.signature == null ? new byte[] {} : client.signature);
                        ex_client.folder_number = client.client_seq;
                        ex_client.client_taken_code = client.client_taken_code;
                        ex_client.cont_id = client.cont_id;
                        ex_client.date_create = client.date_create;
                        ex_client.user_create = client.user_create;
                        ex_client.zone_id = client.zone_id;

                        db.Insert(ex_client);

                        ex_client = db.Table<k_export_client>().OrderByDescending(x => x.export_client_id).First();

                        List<TakenAnalyzeImport> im_analyses = new List<TakenAnalyzeImport>();
                        List<TakenImport> im_takens = new List<TakenImport>();
                        //List<k_taken> _takens = new List<k_taken>();
                        ClientImport im_client = new ClientImport();
                        k_contract _contract = db.Table<k_contract>().Where(c=>c.cont_id==client.cont_id).First();
                        k_contract_h h_contract = new k_contract_h() {
                            active = _contract.active,
                            client_to_invoice = _contract.client_to_invoice,
                            cont_id = _contract.cont_id,
                            cont_number = _contract.cont_number,
                            date_create = _contract.date_create,
                            date_end = _contract.date_end,
                            date_start = _contract.date_start,
                            export_client_id = ex_client.export_client_id,
                            user_create = _contract.user_create
                        };

                        db.Insert(h_contract);
                        List<k_taken_h> h_takens = new List<k_taken_h>();
                        List<k_taken_analyze_h> h_analyzes = new List<k_taken_analyze_h>();

                        foreach (k_taken taken in takens.Where(t => t.client_taken_id == client.client_taken_id))
                        {
                            foreach (k_taken_analyze analyse in analyzes.Where(a => a.taken_id == taken.taken_id))
                            {
                                TakenAnalyzeImport im_a = new TakenAnalyzeImport();
                                k_taken_analyze_h h_an = new k_taken_analyze_h();
                                h_an.taken_id = im_a.taken_id = analyse.taken_id;
                                h_an.analyze_code = im_a.analyze_code = analyse.analyze_code;
                                h_an.analyze_label = im_a.analyze_label = analyse.analyze_label;
                                h_an.analyze_value = im_a.analyze_value = analyse.analyze_value;
                                h_an.date_create = im_a.date_create = analyse.date_create;
                                h_an.sch_id = im_a.sch_id = taken.sch_id;
                                h_an.export_client_id = ex_client.export_client_id;

                                im_analyses.Add(im_a);
                                h_analyzes.Add(h_an);
                                
                            }

                            TakenImport im_t = new TakenImport();
                            k_taken_h h_t = new k_taken_h();
                            h_t.taken_id = im_t.taken_id = taken.taken_id;
                            h_t.prod_code = im_t.prod_code = taken.prod_code;
                            h_t.taken_type = im_t.taken_type = taken.taken_type;
                            h_t.taken_code = im_t.taken_code = taken.taken_code;
                            h_t.client_taken_id = im_t.client_taken_id = taken.client_taken_id;
                            h_t.surv_code = im_t.surv_code = taken.surv_code;
                            h_t.taken_point_code = im_t.taken_point_code = taken.taken_point_code;
                            h_t.taken_point_label = im_t.taken_point_label = taken.taken_point_label;
                            h_t.taken_point_modifiable = im_t.taken_point_modifiable = taken.taken_point_modifiable;
                            h_t.taken_date = im_t.taken_date = taken.taken_date;
                            h_t.days_taken = im_t.days_taken = taken.days_taken;
                            h_t.months_taken = im_t.months_taken = taken.months_taken;
                            h_t.years_taken = im_t.years_taken = taken.years_taken;
                            h_t.taken_comment = im_t.taken_comment = taken.taken_comment;
                            h_t.taken_point_day = im_t.taken_point_day = taken.taken_point_day;
                            h_t.taken_date_next = im_t.taken_date_next = taken.taken_date_next;
                            h_t.taken_date_last = im_t.taken_date_last = taken.taken_date_last;
                            h_t.amount = im_t.amount = taken.amount;
                            h_t.date_create = im_t.date_create = taken.date_create;
                            h_t.sample_number = im_t.sample_number = taken.sample_number;
                            h_t.comment = im_t.comment = taken.comment;
                            h_t.value_01 = im_t.value_01 = taken.value_01;
                            h_t.value_02 = im_t.value_02 = taken.value_02;
                            h_t.value_03 = im_t.value_03 = taken.value_03;
                            h_t.value_04 = im_t.value_04 = taken.value_04;
                            h_t.value_05 = im_t.value_05 = taken.value_05;
                            h_t.value_06 = im_t.value_06 = taken.value_06;
                            h_t.value_07 = im_t.value_07 = taken.value_07;
                            h_t.value_08 = im_t.value_08 = taken.value_08;
                            h_t.value_09 = im_t.value_09 = taken.value_09;
                            h_t.value_10 = im_t.value_10 = taken.value_10;
                            h_t.value_11 = im_t.value_11 = taken.value_11;
                            h_t.value_12 = im_t.value_12 = taken.value_12;
                            im_t.analyze_list = im_analyses;
                            h_t.sch_id = im_t.sch_id = taken.sch_id;
                            h_t.export_client_id = ex_client.export_client_id;
                            h_t.status = im_t.status = taken.status;
                            h_t.reason_delete = im_t.reason_delete = taken.reason_delete;

                            im_takens.Add(im_t);
                            h_takens.Add(h_t);
                            //taken.export_client_id = ex_client.export_client_id;
                            //_takens.Add(taken);
                        }

                        im_client.client_export_id = ex_client.export_client_id;
                        im_client.export_id = export.export_id;
                        im_client.client_id = client.client_taken_id;
                        im_client.folder_number = client.client_seq;
                        im_client.client_signature = client.signature;
                        im_client.signature_label = client.signature_label;
                        im_client.export_status = true;
                        im_client.export_date = DateTime.Now;
                        im_client.export_user = App.CurrentUserId;
                        im_client.tablet_number = App.Marchine;
                        im_client.date_create = DateTime.Now;
                        im_client.taken_list = im_takens;

                        StringContent queryString = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(im_client));

                        HttpResponseMessage response = await hclient.PostAsync(new Uri(string.Format("{0}{1}", App.AppUri, "UploadClient")), queryString);
                        //string responseBodyAsText = await response.Content.ReadAsStringAsync();
                        //var result = (ImportResult)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(ImportResult));

                        //ImportClientResult(result.result);
                        //ex_client.export_status = result.status == 0 ? false : true;
                        ex_client.export_status = true;

                        //db.UpdateAll(_takens);
                        db.Update(ex_client);
                        db.InsertAll(h_takens);
                        db.InsertAll(h_analyzes);
                        //client.signature = null;
                        //client.signature_label = null;
                        //db.Update(client);
                        

                    }

                };

                
                await VerifyData();

                txtVerifData.Text = m.export_Success;
                prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnOK.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            catch (Exception ex)
            {
                txtVerifData.Text = string.Format("{0}{1}{2}", m.export_Fail, (char)13, ex.Message);
                prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnOK.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(BasicPage));
        }

        void ImportClientResult(ClientImportResult result)
        {
            var db = new SQLite.SQLiteConnection(App.DBPath);
            //k_client_taken client = new k_client_taken();
            //client.client_taken_code = result.client_taken_code;
            //client.zone_id = result.zone_id;
            //client.cont_id = result.cont_id;
            //client.user_create = result.user_create;
            //client.date_create = result.date_create;
            //db.Insert(client);
            //client = db.Table<k_client_taken>().OrderByDescending(x => x.client_taken_id).First();

            foreach (TakenImportResult taken_result in result.takens)
            {
                k_taken taken = new k_taken();
                taken.prod_code = taken_result.prod_code;
                taken.taken_type = taken_result.taken_type;
                taken.taken_code = taken_result.taken_code;
                taken.client_taken_id = taken_result.client_taken_id;
                taken.surv_code = taken_result.surv_code;
                taken.taken_point_code = taken_result.taken_point_code;
                taken.taken_point_label = taken_result.taken_point_label;
                taken.taken_point_modifiable = taken_result.taken_point_modifiable;
                taken.taken_date = taken_result.taken_date;
                taken.days_taken = taken_result.days_taken;
                taken.months_taken = taken_result.months_taken;
                taken.years_taken = taken_result.years_taken;
                taken.taken_comment = taken_result.taken_comment;
                taken.taken_point_day = taken_result.taken_point_day;
                taken.taken_date_next = taken_result.taken_date_next;
                taken.taken_date_last = taken_result.taken_date_last;
                taken.amount = taken_result.amount;
                taken.user_create = taken_result.user_create;
                taken.date_create = taken_result.date_create;
                taken.export_client_id = null;
                db.Insert(taken);
                taken = db.Table<k_taken>().OrderByDescending(x => x.taken_id).First();

                List<k_taken_analyze> analyzes = new List<k_taken_analyze>();
                foreach (TakenAnalyzeImportResult analyze_reult in taken_result.analyzes.Where(a => a.taken_id == taken_result.taken_id))
                {
                    k_taken_analyze analyze = new k_taken_analyze();
                    analyze.analyze_code = analyze_reult.analyze_code;
                    analyze.analyze_label = analyze_reult.analyze_label;
                    analyze.taken_id = taken.taken_id;
                    analyze.to_do = analyze_reult.to_do;
                    analyze.user_create = analyze_reult.user_create;
                    analyze.date_create = analyze_reult.date_create;

                    analyzes.Add(analyze);
                }

                db.InsertAll(analyzes);
            }
        }

        void ClearData()
        {
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                // Drop the tables
                db.DropTable<k_client_taken>();
                db.DropTable<k_contract>();
                db.DropTable<k_system_parameter>();
                db.DropTable<k_taken>();
                db.DropTable<k_taken_analyze>();
                db.DropTable<k_user>();
                db.DropTable<k_zone_geographic>();
                db.DropTable<NTIERS_X>();
                db.DropTable<NPRODUIT>();
                db.DropTable<PLANCONT>();
                db.DropTable<SECTEURS>();
                db.DropTable<ANALYSES>();
                db.DropTable<ANAPLAN>();
                db.DropTable<ANAPRD>();
                db.DropTable<IDENT01>();
                db.DropTable<IDENT02>();
                db.DropTable<IDENT03>();
                db.DropTable<IDENT04>();
                db.DropTable<IDENT05>();
                db.DropTable<IDENT06>();
                db.DropTable<IDENT07>();
                db.DropTable<IDENT08>();
                db.DropTable<IDENT09>();
                db.DropTable<IDENT10>();
                db.DropTable<IDENT11>();
                db.DropTable<IDENT12>();
                db.DropTable<PTPREL>();

                // Create the tables if they don't exist
                db.CreateTable<k_client_taken>();
                db.CreateTable<k_contract>();
                db.CreateTable<k_system_parameter>();
                db.CreateTable<k_taken>();
                db.CreateTable<k_taken_analyze>();
                db.CreateTable<k_user>();
                db.CreateTable<k_zone_geographic>();
                db.CreateTable<NTIERS_X>();
                db.CreateTable<NPRODUIT>();
                db.CreateTable<PLANCONT>();
                db.CreateTable<SECTEURS>();
                db.CreateTable<ANALYSES>();
                db.CreateTable<ANAPLAN>();
                db.CreateTable<ANAPRD>();
                db.CreateTable<IDENT01>();
                db.CreateTable<IDENT02>();
                db.CreateTable<IDENT03>();
                db.CreateTable<IDENT04>();
                db.CreateTable<IDENT05>();
                db.CreateTable<IDENT06>();
                db.CreateTable<IDENT07>();
                db.CreateTable<IDENT08>();
                db.CreateTable<IDENT09>();
                db.CreateTable<IDENT10>();
                db.CreateTable<IDENT11>();
                db.CreateTable<IDENT12>();
                db.CreateTable<PTPREL>();
            }
        }

        private async Task VerifyData()
        {
            string uri = App.AppUri;

            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {

                if (!await ValidateUrl(string.Format("{0}{1}", uri, "GetAllUser")))
                {
                    txtVerifData.Text = string.Format("Can't connect to server {0}", uri);

                    return;
                }
                ClearData();
                if (db.Table<k_user>().Count() == 0)
                {
                    txtVerifData.Text = string.Format(new msg().login_Recovery, (char)13);

                    try
                    {
                        //Kalficom.Service1Client myService = new Kalficom.Service1Client();
                        var client = new HttpClient();

                        HttpResponseMessage m = await client.GetAsync(new Uri(string.Format("{0}{1}", uri, "GenerateTakenSchedule")));
                        #region User

                        string responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllUser")));
                        var list_user = (List<k_user>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_user>));
                        db.InsertAll(list_user);

                        #endregion User

                        #region ClientTaken

                        if (db.Table<k_client_taken>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllClientTaken")));
                            var list_client = (List<k_client_taken>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_client_taken>));
                            foreach (k_client_taken k in list_client) db.InsertOrReplace(k);
                        }
                        #endregion ClientTaken

                        #region ZoneGeographic

                        if (db.Table<k_zone_geographic>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllZone")));
                            var list_zone = (List<k_zone_geographic>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_zone_geographic>));
                            db.InsertAll(list_zone);
                        }
                        #endregion ZoneGeographic

                        #region NTIERS_X
                        if (db.Table<NTIERS_X>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllNTIERS_X")));
                            var list_NTIERS_X = (List<NTIERS_X>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<NTIERS_X>));
                            db.InsertAll(list_NTIERS_X);
                        }

                        #endregion NTIERS_X

                        #region Contract

                        if (db.Table<k_contract>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllContract")));
                            var list_contract = (List<k_contract>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_contract>));
                            db.InsertAll(list_contract);
                        }
                        #endregion Contract

                        #region SystemParameter

                        if (db.Table<k_system_parameter>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllSystemParameter")));
                            var list_system = (List<k_system_parameter>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_system_parameter>));
                            db.InsertAll(list_system);
                        }
                        #endregion SystemParameter

                        #region Taken

                        if (db.Table<k_taken>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllTaken")));
                            var list = (List<k_taken>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_taken>));

                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllTakenAnalyze")));
                            var list_analyze = (List<k_taken_analyze>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_taken_analyze>));

                            foreach (k_taken k in list)
                            {
                                k.taken_id_main = k.taken_id;
                                db.Insert(k);

                                List<k_taken_analyze> anas = new List<k_taken_analyze>();
                                foreach (k_taken_analyze ana in list_analyze.Where(a => a.taken_id == k.taken_id_main))
                                {

                                    ana.taken_id = k.taken_id;
                                    ana.sch_id = k.sch_id;
                                    anas.Add(ana);
                                }

                                db.InsertAll(anas);
                            }
                        }
                        #endregion Taken

                        #region TakenAnalyze
                        //if (db.Table<k_taken_analyze>().Count() == 0)
                        //{
                        //    responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllTakenAnalyze")));
                        //    var list_analyze = (List<k_taken_analyze>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_taken_analyze>));
                        //    db.InsertAll(list_analyze);
                        //}
                        #endregion TakenAnalyze

                        #region NPRODUIT
                        if (db.Table<NPRODUIT>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllNproduit")));
                            var list_NPRODUIT = (List<NPRODUIT>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<NPRODUIT>));
                            db.InsertAll(list_NPRODUIT);
                        }
                        #endregion NPRODUIT

                        #region PLANCOUNT
                        if (db.Table<PLANCONT>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllPlanCont")));
                            var list_PLANCONT = (List<PLANCONT>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<PLANCONT>));
                            db.InsertAll(list_PLANCONT);
                        }
                        #endregion PLANCOUNT

                        #region SECTEURS
                        if (db.Table<SECTEURS>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllSecteur")));
                            var list_SECTEURS = (List<SECTEURS>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<SECTEURS>));
                            db.InsertAll(list_SECTEURS);
                        }
                        #endregion SECTEURS

                        #region ANALYSES
                        if (db.Table<ANALYSES>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllAnalyse")));
                            var list_ANALYSES = (List<ANALYSES>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<ANALYSES>));
                            db.InsertAll(list_ANALYSES);
                        }
                        #endregion ANALYSES

                        #region ANAPLAN
                        if (db.Table<ANAPLAN>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllAnaPlan")));
                            var list_ANAPLAN = (List<ANAPLAN>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<ANAPLAN>));
                            db.InsertAll(list_ANAPLAN);
                        }
                        #endregion ANAPLAN

                        #region ANAPRD
                        if (db.Table<ANAPRD>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllAnalyseProduit")));
                            var list_ANAPRD = (List<ANAPRD>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<ANAPRD>));
                            db.InsertAll(list_ANAPRD);
                        }
                        #endregion ANAPRD

                        #region IDENT01
                        if (db.Table<IDENT01>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent01")));
                            var list_IDENT01 = (List<IDENT01>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT01>));
                            db.InsertAll(list_IDENT01);
                        }
                        #endregion IDENT01

                        #region IDENT02
                        if (db.Table<IDENT02>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent02")));
                            var list_IDENT02 = (List<IDENT02>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT02>));
                            db.InsertAll(list_IDENT02);
                        }
                        #endregion IDENT02

                        #region IDENT03
                        if (db.Table<IDENT03>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent03")));
                            var list_IDENT03 = (List<IDENT03>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT03>));
                            db.InsertAll(list_IDENT03);
                        }
                        #endregion IDENT03

                        #region IDENT04
                        if (db.Table<IDENT04>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent04")));
                            var list_IDENT04 = (List<IDENT04>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT04>));
                            db.InsertAll(list_IDENT04);
                        }
                        #endregion IDENT04

                        #region IDENT05
                        if (db.Table<IDENT05>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent05")));
                            var list_IDENT05 = (List<IDENT05>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT05>));
                            db.InsertAll(list_IDENT05);
                        }
                        #endregion IDENT05

                        #region IDENT06
                        if (db.Table<IDENT06>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent06")));
                            var list_IDENT06 = (List<IDENT06>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT06>));
                            db.InsertAll(list_IDENT06);
                        }
                        #endregion IDENT06

                        #region IDENT07
                        if (db.Table<IDENT07>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent07")));
                            var list_IDENT07 = (List<IDENT07>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT07>));
                            db.InsertAll(list_IDENT07);
                        }
                        #endregion IDENT07

                        #region IDENT08
                        if (db.Table<IDENT08>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent08")));
                            var list_IDENT08 = (List<IDENT08>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT08>));
                            db.InsertAll(list_IDENT08);
                        }
                        #endregion IDENT08

                        #region IDENT09
                        if (db.Table<IDENT09>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent09")));
                            var list_IDENT09 = (List<IDENT09>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT09>));
                            db.InsertAll(list_IDENT09);
                        }
                        #endregion IDENT09

                        #region IDENT10
                        if (db.Table<IDENT10>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent10")));
                            var list_IDENT10 = (List<IDENT10>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT10>));
                            db.InsertAll(list_IDENT10);
                        }
                        #endregion IDENT10

                        #region IDENT11
                        if (db.Table<IDENT11>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent11")));
                            var list_IDENT11 = (List<IDENT11>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT11>));
                            db.InsertAll(list_IDENT11);
                        }
                        #endregion IDENT11

                        #region IDENT12
                        if (db.Table<IDENT12>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent12")));
                            var list_IDENT12 = (List<IDENT12>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT12>));
                            db.InsertAll(list_IDENT12);
                        }
                        #endregion IDENT12

                        #region PTPREL
                        if (db.Table<PTPREL>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllPtprel")));
                            var list_PTPREL = (List<PTPREL>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<PTPREL>));
                            db.InsertAll(list_PTPREL);
                        }
                        #endregion PTPREL

                        //VerifyTakenCollection();

                        txtVerifData.Text = string.Format(new msg().login_RecoverySuccess, (char)13);
                        prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        btnOK.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }
                    catch (Exception ex)
                    {
                        txtVerifData.Text = ex.Message;
                    }

                }
            }
        }

        internal static async Task<bool> ValidateUrl(string url)
        {
            try
            {
                Uri validUri;
                if (Uri.TryCreate(url, UriKind.Absolute, out validUri))
                {
                    var client = new HttpClient();

                    var response = await client.GetAsync(validUri, HttpCompletionOption.ResponseHeadersRead);
                    return response.IsSuccessStatusCode;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
    }
}
